﻿using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace LitBT
{
    /// <summary>
    /// 行为树编辑窗口
    /// </summary>
    public class BehaviourTreeEditor : EditorWindow
    {
        BehaviourTreeView treeView;
        InspectorView inspectorView;

        [MenuItem("Tools/LitBT/BehaviourTreeEditor")]
        public static void ShowEmptyGraph()
        {
            BehaviourTreeEditor wnd = GetWindow<BehaviourTreeEditor>();
            wnd.titleContent = new GUIContent("BehaviourTreeEditor");
            wnd.Show();
        }

        public void CreateGUI()
        {
            VisualElement root = rootVisualElement;

            var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>
                ("Assets/_ToolList/BehaviourTree/Editor/BehaviourTreeEditor.uxml");
            visualTree.CloneTree(root);

            var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>
                ("Assets/_ToolList/BehaviourTree/Editor/BehaviourTreeEditor.uss");
            root.styleSheets.Add(styleSheet);

            treeView = root.Q<BehaviourTreeView>();
            inspectorView = root.Q<InspectorView>();
            treeView.OnNodeSelected = OnNodeSelectionChanged;
        }

        /// <summary>
        /// 选择节点
        /// </summary>
        /// <param name="node"></param>
        void OnNodeSelectionChanged(NodeView node)
        {
            inspectorView.UpdateSelection(node);
        }

        /// <summary>
        /// 显示树的图
        /// </summary>
        /// <param name="tree"></param>
        public void ShowTreeGraph(BehaviourTree tree)
        {
            if (tree && AssetDatabase.CanOpenAssetInEditor(tree.GetInstanceID()))
            {
                treeView.PopulateView(tree);
            }
        }
    }
}